package com.yang.demo.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.yang.demo.entity.*;
import com.yang.demo.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaoyang
 * @since 2022-07-09
 */
@Api(tags = "员工管理接口")
@RestController
@RequestMapping("/systemctl/basic/employee/")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPoliticsStatusService politicsStatusService;
    @Autowired
    private IJoblevelService joblevelService;
    @Autowired
    private INationService nationService;
    @Autowired
    private IPositionService positionService;
    @Autowired
    private IDepartmentService departmentService;

    @ApiOperation(value = "分页查询员工")
    @GetMapping("/")
    public RespPageBean getAllEmployees(@RequestParam(defaultValue = "1") Integer currentPage,
                                        @RequestParam(defaultValue = "10")Integer size,
                                        Employee employee,
                                        LocalDate[] beginDateScope){
        return employeeService.getEmployeesByPage(currentPage,size,employee,beginDateScope);
    }

    @ApiOperation(value = "获取政治面貌")
    @GetMapping("politicsStatuses")
    public List<PoliticsStatus> getAllPoliticsStatus(){
        return politicsStatusService.list();
    }

    @ApiOperation(value = "获取所有职称")
    @GetMapping("joblevels")
    public List<Joblevel> getAllJobleves(){
        return joblevelService.list();
    }

    @ApiOperation(value = "获取所有民族")
    @GetMapping("nations")
    public List<Nation> getAllNations(){
        return nationService.list();
    }

    @ApiOperation(value = "获取所有职位")
    @GetMapping("positions")
    public List<Position> getAllPositions(){
        return positionService.list();
    }

    @ApiOperation(value = "获取所有部门")
    @GetMapping("departments")
    public List<Department> departments(){
        return departmentService.getAllDepartment();
    }

    @ApiOperation(value = "获取最大的工号id")
    @GetMapping("maxWorkId")
    public RespBean getMaxWorkId(){
        return employeeService.getMaxWorkId();
    }

    @ApiOperation(value = "添加员工")
    @PostMapping("addWorker")
    public RespBean addWork(@RequestBody Employee employee){
        return employeeService.addWork(employee);
    }

    @ApiOperation(value = "修改员工")
    @PutMapping("updateWorker")
    public RespBean updateWorker(@RequestBody Employee employee) {
        return employeeService.updateWorker(employee);
    }

    @ApiOperation(value = "删除员工")
    @PutMapping("/{id}")
    public RespBean updateWorker(@PathVariable Integer id){
        if (employeeService.removeById(id)){
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation(value = "导出员工数据")
    @GetMapping(value = "/exportEmployee" ,produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response){
        //导出的excel表格，用流额形式，也不需要返回RespBean
        List<Employee> employees = employeeService.exportEmployee(null);
        // HSSF 03版的excel兼容性好,导出速度快
        ExportParams exportParams = new ExportParams("员工类型", "员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Employee.class, employees);
        ServletOutputStream outputStream = null;
        try {
            //以流的形式传出
            response.setHeader("content-type","application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition","attachment;filename="
                    + URLEncoder.encode("员工表.xls","UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导入员工数据")
    @PostMapping("importEmployee")
    public RespBean importEmployee(MultipartFile file){
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        List<Nation> nationList = nationService.list();
        List<Joblevel> joblevelList = joblevelService.list();
        List<Department> departmentList = departmentService.list();
        List<Position> positionList = positionService.list();
        try {
            List<Employee> employeeList = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, importParams);
            employeeList.forEach(employee -> {
                nationList.get(nationList.indexOf(new Nation(employee.getNation().getName()))).getId();
                joblevelList.get(joblevelList.indexOf(new Joblevel(employee.getJoblevel().getName()))).getId();
                departmentList.get(departmentList.indexOf(new Department(employee.getDepartment().getName()))).getId();
                positionList.get(positionList.indexOf(new Position(employee.getPosition().getName()))).getId();
            });
            if (employeeService.saveBatch(employeeList)){
                return RespBean.success("导入成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败");
    }

}
